<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { qingyunMapData } from "@/utils/qingyun";

let map = null;
let districtLayer = null;
let geoJsonLayer = null;
const loading = ref(true);

// 庆云县中心坐标
const QINGYUN_CENTER = [117.390507, 37.777724];

// 初始化地图
const initMap = async () => {
    try {
        window._AMapSecurityConfig = {
            securityJsCode: import.meta.env.VITE_AMAP_SECURITY_JS_CODE,
        };

        const AMap = await AMapLoader.load({
            key: import.meta.env.VITE_AMAP_KEY,
            version: import.meta.env.VITE_AMAP_VERSION,
            plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.DistrictLayer", "AMap.GeoJSON"],
        });

        // 创建地图实例 - 纯边界模式
        map = new AMap.Map("container", {
            viewMode: "2D", // 使用2D模式更适合行政区域展示
            zoom: 10, // 适合庆云县的缩放级别
            center: QINGYUN_CENTER, // 设置为庆云县中心
            mapStyle: "amap://styles/normal", // 使用标准主题
            showLabel: false,
            features: [], // 完全移除底图要素
            showBuildingBlock: false,
            showIndoorMap: false,
            terrain: false,
            skyColor: "transparent"
        });

        // 添加地图控件
        map.addControl(new AMap.Scale());
        map.addControl(new AMap.ToolBar());

        // 添加庆云县行政区域
        addQingyunDistrict(AMap);

        loading.value = false;
    } catch (error) {
        console.error("地图加载失败:", error);
        loading.value = false;
    }
};

// 添加庆云县行政区域
const addQingyunDistrict = (AMap) => {
    // 创建GeoJSON图层 - 纯边界线条
    geoJsonLayer = new AMap.GeoJSON({
        geoJSON: qingyunMapData,
        // 设置样式
        getPolygon: (geojson, lnglats) => {
            return new AMap.Polygon({
                path: lnglats,
                fillColor: "rgba(59, 130, 246, 0.08)", // 极淡的填充
                strokeColor: "#2563eb", // 鲜明的边界色
                strokeWeight: 2.5, // 适中的边界线
                fillOpacity: 0.1, // 填充透明度
                strokeOpacity: 1, // 边框透明度
                strokeStyle: "solid", // 边框样式
                cursor: "pointer",
                zIndex: 100
            });
        },
    });

    // 添加到地图
    map.add(geoJsonLayer);

    // 添加点击事件
    geoJsonLayer.on("click", (e) => {
        const props = e.target.getExtData();
        if (props && props.properties) {
            console.log("点击了区域:", props.properties.name);
            // 这里可以添加更多交互逻辑
            showDistrictInfo(props.properties);
        }
    });

    // 添加鼠标悬停效果
    geoJsonLayer.on("mouseover", (e) => {
        e.target.setOptions({
            fillColor: "rgba(255, 193, 7, 0.4)",
            fillOpacity: 0.5,
        });
    });

    geoJsonLayer.on("mouseout", (e) => {
        e.target.setOptions({
            fillColor: "rgba(0, 123, 255, 0.2)",
            fillOpacity: 0.3,
        });
    });

    // 自适应显示
    map.setFitView([geoJsonLayer], false, [20, 20, 20, 20]);
};

// 显示区域信息
const showDistrictInfo = (properties) => {
    const infoWindow = new AMap.InfoWindow({
        content: `
      <div style="padding: 10px; min-width: 200px;">
        <h3 style="margin: 0 0 10px 0; color: #333;">${properties.name}</h3>
        <p style="margin: 5px 0; color: #666;">行政区划代码: ${properties.adcode || '371423'}</p>
        <p style="margin: 5px 0; color: #666;">中心坐标: ${QINGYUN_CENTER.join(', ')}</p>
        <p style="margin: 5px 0; color: #666;">行政级别: 县级</p>
      </div>
    `,
        offset: new AMap.Pixel(0, -30),
    });

    infoWindow.open(map, QINGYUN_CENTER);
};

onMounted(() => {
    initMap();
});

// 控制按钮方法
const resetView = () => {
    if (map) {
        map.setZoomAndCenter(10, QINGYUN_CENTER);
        // 关闭所有信息窗口
        map.clearInfoWindow();
    }
};

// 边界样式状态
let currentBoundaryStyle = 0;
const boundaryStyles = [
  {
    fillColor: 'rgba(59, 130, 246, 0.08)',
    strokeColor: '#2563eb',
    strokeWeight: 2.5,
    name: '标准蓝色'
  },
  {
    fillColor: 'rgba(34, 197, 94, 0.08)',
    strokeColor: '#16a34a',
    strokeWeight: 2.5,
    name: '清新绿色'
  },
  {
    fillColor: 'rgba(239, 68, 68, 0.08)',
    strokeColor: '#dc2626',
    strokeWeight: 2.5,
    name: '醒目红色'
  },
  {
    fillColor: 'rgba(168, 85, 247, 0.08)',
    strokeColor: '#9333ea',
    strokeWeight: 2.5,
    name: '优雅紫色'
  }
];

const toggleBoundaryStyle = () => {
  if (map && geoJsonLayer) {
    currentBoundaryStyle = (currentBoundaryStyle + 1) % boundaryStyles.length;
    const style = boundaryStyles[currentBoundaryStyle];
    
    // 更新图层样式
    geoJsonLayer.setOptions({
      getPolygon: function(geojson, lnglats) {
        return new AMap.Polygon({
          path: lnglats,
          fillColor: style.fillColor,
          strokeColor: style.strokeColor,
          strokeWeight: style.strokeWeight,
          fillOpacity: 0.1,
          strokeOpacity: 1,
          cursor: 'pointer',
          strokeStyle: 'solid',
          zIndex: 100
        });
      }
    });
    
    // 显示样式切换提示
    const infoWindow = new AMap.InfoWindow({
      content: `<div style="padding: 10px; text-align: center;">边界样式已切换为: <strong>${style.name}</strong></div>`,
      offset: new AMap.Pixel(0, -30),
      closeWhenClickMap: true,
      autoMove: false
    });
    infoWindow.open(map, QINGYUN_CENTER);
    
    // 3秒后自动关闭提示
    setTimeout(() => {
      infoWindow.close();
    }, 2000);
  }
};

const showFullInfo = () => {
    if (map) {
        let infoContent = '<div style="padding: 15px; max-width: 400px; font-family: Arial, sans-serif;">';
        infoContent += '<h3 style="margin: 0 0 15px 0; color: #333; border-bottom: 2px solid #007bff; padding-bottom: 8px;">庆云县行政区域详情</h3>';

        infoContent += `
      <div style="margin: 12px 0; padding: 12px; background: #f8f9fa; border-left: 4px solid #007bff; border-radius: 4px;">
        <div style="font-weight: bold; color: #333; margin-bottom: 6px; font-size: 16px;">庆云县</div>
        <div style="color: #666; font-size: 14px; line-height: 1.5;">
          <div><strong>行政代码:</strong> 371423</div>
          <div><strong>中心坐标:</strong> [${QINGYUN_CENTER[0]}, ${QINGYUN_CENTER[1]}]</div>
          <div><strong>层级:</strong> 县级</div>
          <div><strong>上级区域:</strong> 山东省德州市</div>
        </div>
      </div>
    `;

        infoContent += '<div style="margin-top: 15px; padding-top: 10px; border-top: 1px solid #ddd; color: #888; font-size: 12px; text-align: center;">点击地图区域查看详细信息</div>';
        infoContent += '</div>';

        const infoWindow = new AMap.InfoWindow({
            content: infoContent,
            offset: new AMap.Pixel(0, -30),
            closeWhenClickMap: true
        });
        infoWindow.open(map, QINGYUN_CENTER);
    }
};

onUnmounted(() => {
    if (map) {
        map.destroy();
        map = null;
    }
});
</script>

<template>
    <div class="map-wrapper">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-overlay">
            <div class="loading-content">
                <div class="spinner"></div>
                <p>正在加载庆云县地图...</p>
            </div>
        </div>

        <!-- 地图容器 -->
        <div id="container" class="map-container"></div>

        <!-- 地图控制面板 -->
        <div class="map-controls">
            <div class="control-panel">
                <h3>庆云县行政区域规划</h3>
                <div class="control-buttons">
                    <button @click="resetView" class="control-btn">
                        <span>🏠</span> 重置视图
                    </button>
                    <button @click="toggleBoundaryStyle" class="control-btn">
             <span>🎨</span> 边界样式
           </button>
                    <button @click="showFullInfo" class="control-btn">
                        <span>ℹ️</span> 区域信息
                    </button>
                </div>
                <div class="map-info">
                    <p><strong>区域:</strong> 庆云县</p>
                    <p><strong>行政代码:</strong> 371423</p>
                    <p><strong>所属:</strong> 山东省德州市</p>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.map-wrapper {
    position: relative;
    width: 100%;
    height: 800px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.map-container {
  width: 100%;
  height: 100%;
  background: #f8f9fa; /* 设置干净的背景色 */
}

/* 隐藏高德地图底图瓦片 */
.map-container :deep(.amap-layers) {
  display: none !important;
}

/* 只显示我们的矢量图层 */
.map-container :deep(.amap-overlays) {
  display: block !important;
}

/* 隐藏高德地图的版权信息 */
.map-container :deep(.amap-copyright) {
  display: none !important;
}

/* 隐藏高德地图的logo */
.map-container :deep(.amap-logo) {
  display: none !important;
}

/* 加载状态样式 */
.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.loading-content {
    text-align: center;
    color: #666;
}

.spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #007bff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto 16px;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

/* 控制面板样式 */
.map-controls {
    position: absolute;
    top: 20px;
    right: 20px;
    z-index: 999;
}

.control-panel {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    min-width: 200px;
    backdrop-filter: blur(10px);
}

.control-panel h3 {
    margin: 0 0 12px 0;
    font-size: 16px;
    color: #333;
    border-bottom: 2px solid #007bff;
    padding-bottom: 8px;
}

.control-buttons {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 16px;
}

.control-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background: white;
    color: #333;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 14px;
}

.control-btn:hover {
    background: #f8f9fa;
    border-color: #007bff;
    color: #007bff;
}

.control-btn:active {
    transform: translateY(1px);
}

.map-info {
    border-top: 1px solid #eee;
    padding-top: 12px;
}

.map-info p {
    margin: 4px 0;
    font-size: 12px;
    color: #666;
}

.map-info strong {
    color: #333;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .map-controls {
        top: 10px;
        right: 10px;
        left: 10px;
    }

    .control-panel {
        padding: 12px;
    }

    .control-buttons {
        flex-direction: row;
        flex-wrap: wrap;
    }

    .control-btn {
        flex: 1;
        min-width: 0;
        font-size: 12px;
        padding: 6px 8px;
    }
}
</style>
